package uk.ac.glasgow.demosocs.impl.election;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import uk.ac.glasgow.demosocs.Candidate;
import uk.ac.glasgow.demosocs.ElectionResult;
import uk.ac.glasgow.demosocs.users.CandidateImpl;

public class ElectionResultImpl implements ElectionResult, Serializable {
	
	
	//results for the election
	private List<Candidate> mResults;
	
	// information in the election
	private ElectionImpl mTheElection;
	
	public ElectionResultImpl(ElectionImpl election){
		mResults = new ArrayList<Candidate>();
		mTheElection = election;
	}
	
	@Override
	public List<Candidate> getWinningCandidates() {
		computeResult();
		return mResults;
	}
	
	void computeResult(){
		/**
		 * as an example we will calculate the candidates with the largest number of votes, based on the ranking of votes
		 * and set them to the mResults list,there is no order difference
		 */
		int bestvotes = getBestVotes();
		//add all candidate who has the best votes to the result list
		//there is no difference in order
		for(CandidateImpl can : mTheElection.getCandidateImplSet()){
			if(can.getVotes() == bestvotes)
				mResults.add(can);
		}
		
	}
	
	public void setElection(ElectionImpl election){
		mTheElection = election;
	}
	
	/**
	 * return the results in string
	 * @return string of the result
	 */
	public String getResult(){
		computeResult();
		/**
		 * do publish result
		 */
		String restring = "The result for election: "+mTheElection.getElectionName()+" Election ID: "+
				mTheElection.getEID()+" :\n";
		for(Candidate can : mResults){
			CandidateImpl canimp = mTheElection.getCandidateByGUID(can.getGUID());
			restring+= "Candidate Surname:"+can.getCandidateSurname()+" Forename: "+can.getCandidateForename()+" GUID: "+can.getGUID()+
					" Votes: "+canimp.getVotes()+"\n";
		}
		return restring;
	}
	
	/**
	 * find out the best votes for candidates in the election
	 * @return int - best votes
	 */
	private int getBestVotes(){
		int best = 0;
		for(CandidateImpl can : mTheElection.getCandidateImplSet()){
			if(can.getVotes() >= best)
				best = can.getVotes();
		}
		
		return best;
	}
}
